//
//  APPLEAuthViewController.swift
//  123
//
//  Created by pangjiaxing on 15/12/30.
//  Copyright © 2015年 pangjiaxing. All rights reserved.
//

import UIKit
import SVProgressHUD

class APPLEAuthViewController: UIViewController,UIWebViewDelegate {

var WB_APPKEY = "956193458"
var WB_REGIRECTURI = "http://www.itheima.com/"
var WB_SECRET = "1c397c063bbe267c4ccac42b30ff8157"
    
    private lazy var webView:UIWebView = {
        let webView=UIWebView()
        webView.delegate=self
        return webView
    }()
    
    override func loadView() {
        view=webView
        setupUI()
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APPKEY)&redirect_uri=\(WB_REGIRECTURI)"
        let url = NSURL(string: urlString)
        guard let _ = url else{
            print("APPLEAuthViewController 第一个 url 为空")
            return
        }
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    
    private func setupUI(){
        navigationItem.title = "新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", targat: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", targat: self, action: "autoFill")
    }
    @objc private func close(){
        dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss()
    }
    @objc private func autoFill(){
        let jsString = "document.getElementById('userId').value='18234097085';document.getElementById('passwd').value='yanghaiying100';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    
   
  
    
    
   
}


extension APPLEAuthViewController{
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print("11111-----\(request.URL?.absoluteString)")
        guard let urlString = request.URL?.absoluteString else {
            return true
        }
        
        if !urlString.hasPrefix(WB_REGIRECTURI){
            return true
        }
        print("22222------\(request.URL?.query)")
        if let quary = request.URL?.query where quary.hasPrefix("code="){
            
            
        let  code = quary.substringFromIndex("code=".endIndex)
            
            APPLEUserAccountViewModel.sharedViewModel.loadAccessToken(code, compeleted: { (isSuccess) -> () in
                if isSuccess  {
                    print("个人信息加载完成，轻推送控制器，显示数据")
                    SVProgressHUD.dismiss()
                    print("")
                    // 把当前界面消失之后再发送切换根控制器的通知
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        NSNotificationCenter.defaultCenter().postNotificationName("HMSwitchRootViewControllerNotification", object: self)
                    })

                    
                }else{
                    print("请求失败")
                }
            })
            
        }else{
            
            close()
        }
        
        
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}






